<template>
  <div class="point-of-interest">
    <div ref="chart" class="thechart"></div>
    <div class="label-info">{{labelInfo}}</div>
    <div class="sub-components">
      <poi-raw ref="poi-raw"></poi-raw>
      <poi-feature ref="poi-feature"></poi-feature>
    </div>
    <!-- <button ref="reset-zoom" class="resetzoom">Reset Zoom</button> -->
    <!-- <textarea type="text" class="copydata" value="copydata" ref="textarea" /> -->
  </div>
</template>

<script>
import PoiRaw from "./PoiRaw";
import PoiFeature from "./PoiFeature";
import axios from "axios";
import randomcolor from "randomcolor";
import Color from "color";
import * as jsonBeautify from "json-beautify";
let clipboardjs = require("clipboard");
import { round, min, max, map,flatten } from "lodash";
const libDP = require("../lib/Douglas-Peucker");
import * as echarts from "echarts";

const MAP_IMAGES = {
  Vikendi:
    "http://n1-q.mafengwo.net/s16/M00/1F/16/CoUBUl6J6-WAfTq9ABN1dkMMLI4971.jpg#DihorOtok_Main",
  "Erangel (Remastered)":
    "http://n1-q.mafengwo.net/s16/M00/24/CD/CoUBUl6J8CGAZ8FWACwGssFmNzs911.jpg#Baltic_Main.jpg.jpg",
  Miramar:
    "http://b1-q.mafengwo.net/s16/M00/25/07/CoUBUl6J8DuABPwhAB3VGbsEWx0692.jpg#Desert_Main.jpg.jpg",
  Erangel:
    "http://n1-q.mafengwo.net/s16/M00/25/14/CoUBUl6J8E-AbIDmABcvo6NWiPE512.jpg#Erangel_Main.jpg.jpg",
  Sanhok:
    "https://qimage.owhat.cn/prod/master/image/e998aac9-462c-46ce-9c96-0e9506af0da5#Sanhok_Main_High_Res.jpg"
};
const MAP_LENGTH_CENTIMETERS = {
  Vikendi: 612000,
  "Erangel (Remastered)": 816000,
  Miramar: 816000,
  Erangel: 816000,
  Sanhok: 408000
};
const MAP_NAME = "Sanhok";
const MapGameLength = MAP_LENGTH_CENTIMETERS[MAP_NAME];
const MapSize = 1000;
let _scale = MapSize / MapGameLength;
export default {
  name: "POI",
  components: { PoiRaw, PoiFeature },
  data() {
    return {
      copydata: "123",
      labelInfo: " "
    };
  },
  async mounted() {
    let vue = this;
    let ele = this.$refs["chart"];
    let chart = echarts.init(ele, "", {
      renderer: "canvas"
    });
    let grid_sssssize = 500;
    let gridPosition = {
      right: 0,
      // right: 10,
      // bottom: 300,
      top: 0,
      width: grid_sssssize,
      height: grid_sssssize
    };
    let series = await this.getSeries();
    // debugger;
    let optBrush = {
      brushLink: series
        .map((e, i) => {
          if (e._needBrush) return i;
          else return -1;
        })
        .filter(e => e > -1),
      xAxisIndex: [0, 1],
      yAxisIndex: [0, 1],
      toolbox: ["rect", "polygon", "keep", "clear", "lineX", "lineY"],
      inBrush: {
        opacity: 1,
        color: "red",
        colorSaturation: 1
      },
      outOfBrush: {
        opacity: 0.3,
        symbolSize: 5,
        color: "rgba(0,0,0,0.8)"
        // colorSaturation: 0
      },
      brushStyle: {
        borderWidth: 1,
        color: "rgba(0,0,180,0.2)",
        borderColor: "rgba(120,140,180,0.8)"
      },
      throttleType: "debounce",
      throttleDelay: 1000
    };

    chart.setOption({
      backgroundColor: "transparent" || "white",
      color: ["#c23531", "#91c7ae", "#dd8668"],
      brush: optBrush,
      tooltip: {
        trigger: "item"
      },
      toolbox: {
        left: 0
      },
      dataZoom: [
        { type: "inside", xAxisIndex: [0], filterMode: "none" },
        { type: "inside", yAxisIndex: [0], filterMode: "none" },
        { type: "inside", xAxisIndex: [1], filterMode: "none" },
        { type: "inside", yAxisIndex: [1], filterMode: "none" }
      ],
      grid: [
        {
          ...gridPosition,
          show: true,
          backgroundColor: "transparent"
          // z: -200
        },
        {
          left: gridPosition.left + gridPosition.width,
          top: gridPosition.top,
          width: gridPosition.width,
          height: gridPosition.height,
          show: true,
          backgroundColor: "white"
        }
      ],
      xAxis: [
        {
          type: "value",
          max: MapGameLength,
          splitLine: {
            show: false
          },
          axisLine: {},
          gridIndex: 0
        },
        {
          type: "value",
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          axisTick: {
            show: false
          },
          gridIndex: 1
        }
      ],
      yAxis: [
        {
          type: "value",
          max: MapGameLength,
          splitLine: {
            show: false
          },
          inverse: true,
          gridIndex: 0,

          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        {
          type: "value",
          max:50,
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          axisTick: {
            show: false
          },
          gridIndex: 1
        }
      ],
      series: [...series]
    });
    chart.on("brushselected", async params => {
      if (
        params.batch &&
        params.batch[0] &&
        params.batch[0].areas &&
        params.batch[0].areas[0]
      ) {
        // debugger;
        let tsneSeries = params.batch[0].selected.filter(
          e => e.seriesName === "tsne"
        )[0];
        // debugger
        let tsneSelectedIndexes = tsneSeries.dataIndex;

        let poiRaw = this.$refs["poi-raw"];
        let poiFeature = this.$refs["poi-feature"];

        poiRaw.selectedInput(tsneSelectedIndexes);
        poiFeature.selectedInput(tsneSelectedIndexes);

        let tsneData = await vue.singletonTsne;
        let selectedItems = tsneData.filter((e, i) =>
          tsneSelectedIndexes.includes(i)
        );
        let qianwuCount = selectedItems.filter(e => e.ranking <= 5).length;
        let chijiCount = selectedItems.filter(e => e.ranking <= 1).length;
        let labelInfo = `前五率：${round(
          (qianwuCount / selectedItems.length) * 100,
          2
        )}% | 吃鸡率：${round((chijiCount / selectedItems.length) * 100, 2)}%`;
        // console.log(labelInfo);
        vue.labelInfo = labelInfo;
        // debugger;

        // copy()
        let store = {
          points: params.batch[0].areas[0].coordRange
        };
        // console.log(store.save_type, store.points);
        // // debugger
        let text = jsonBeautify(store, null, 2, 50); //||JSON.stringify(store);

        vue.$refs["textarea"].value = text;
        vue.$refs["textarea"].select();
        document.execCommand("copy");

        console.log("复制成功", params.batch[0].areas[0].coordRange.length);
      }
      // debugger
    });
    chart.dispatchAction({
      type: "dataZoom",
      dataZoomIndex: [0, 1],
      start: 15,
      end: 90
    });
    // debugger
    // vue.$refs["reset-zoom"].onclick = () => {
    //   chart.dispatchAction({
    //     type: "dataZoom",
    //     start: 0,
    //     end: 100
    //   });
    // };
  },
  computed: {
    singletonTsne: function() {
      return this.ajaxTsneOf0323();
    }
  },
  methods: {
    ajaxData0318() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/a0fd52e8-e45a-4983-88e5-34f4878c9365#50米";
      link =
        "https://qimage.owhat.cn/prod/master/image/fdd0ae1b-0b58-411a-abcc-0c8b6fcb4d3c#30米";
      // link = "https://qimage.owhat.cn/prod/master/image/b17a670d-be25-4ed3-a271-6eac2d2df198#20米";
      // link = "https://qimage.owhat.cn/prod/master/image/c0c014da-2c24-46f5-ac15-0bcb96fdfae4#10米";
      link =
        "https://qimage.owhat.cn/prod/master/image/334f56c5-fd9a-4a3e-b40d-aef124a6ab55#15米";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    ajaxPoiData0319() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/e27ac3b6-1c6f-4228-aae6-640d36f057a2";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    ajaxPoisOfGuiji() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/3df175fa-5335-47a3-a0d7-1eaf8b0331b6";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    ajaxKuangxuan() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/99e07b9c-d73e-4d48-aa11-4632f71e7746";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    ajaxTsneOf0323() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/8b91dea2-4edf-4957-b33e-e08db1aeef21";
      link =
        "https://qimage.owhat.cn/prod/master/image/86e78c48-054b-4bd1-b3f5-57f5f2ba8b16";
      // link = "https://qimage.owhat.cn/prod/master/image/736acc55-e8a8-4921-860d-e9e6fd90327e"
      // link = "https://qimage.owhat.cn/prod/master/image/e10b7475-78f4-444c-b254-553d2f1d681e"
      link =
        "https://qimage.owhat.cn/prod/master/image/dba95696-ec1a-4952-aeaa-02deef4957a8";
      link =
        "https://qimage.owhat.cn/prod/master/image/cf5d0023-b2fb-470e-a8cb-20d8c9960afc";
      link =
        "https://qimage.owhat.cn/prod/master/image/4e098ec2-9962-4e2f-a756-26b37780458b";
      link =
        "https://qimage.owhat.cn/prod/master/image/33ff55a5-9548-44e5-887a-67f4838e3130";
      link =
        "https://qimage.owhat.cn/prod/master/image/6341fedf-6be0-4ceb-ba35-ce9031e9829a#xiugai";
      link =
        "https://qimage.owhat.cn/prod/master/image/51075d32-01fc-470a-b20f-bbf11a4a1a58";
      // link =
      //   // "https://qimage.owhat.cn/prod/master/image/4a1d1810-aee9-4fb1-bacc-b4a41b7f3ca4";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    async getSeries() {
      let seriesBackground = {
        type: "custom",
        _needBrush: false,
        data: [[408000, 0]],
        coordinateSystem: "cartesian2d",
        xAxisIndex: 0,
        yAxisIndex: 0,
        z: -1,
        silent: true,
        renderItem: function(params, api) {
          let x = [408000, 408000];
          // debugger
          let coord1 = api.coord([0, 0]);
          let coord2 = api.coord([408000, 408000]);
          return {
            type: "group",
            children: [
              {
                type: "rect",
                shape: {
                  x: coord1[0],
                  y: coord1[1],
                  width: coord2[0] - coord1[0],
                  height: coord2[1] - coord1[1]
                },
                style: {
                  stroke: "blue",
                  lineWidth: 0.1,
                  fill: "rgba(202,202,235,0)"
                }
              },
              {
                type: "image",
                style: {
                  image: MAP_IMAGES[MAP_NAME],
                  x: coord1[0],
                  y: coord1[1],
                  width: coord2[0] - coord1[0],
                  height: coord2[1] - coord1[1],
                  opacity: 0.5
                  // fill:"blue"
                }
              }
            ]
          };
        },
        itemStyle: {
          opacity: 0
        }
      };
      let cluster_data = await this.ajaxData0318();
      // debugger;
      let seriesClusterScatter = cluster_data.map(clu => {
        let color_cluster = randomcolor({ luminosity: "dark" });
        // debugger
        return {
          type: "scatter",
          _needBrush: false,
          data: clu.map(p => [p.x, p.y]),
          itemStyle: {
            borderWidth: 1,
            borderColor: "white",
            color: color_cluster,
            opacity: 0.8
          },
          silent: true,
          animation: false
        };
      });
      let data0323 = await this.singletonTsne;
      let all_pois_count = {};
      for (let rrr of data0323) {
        for (let i = 1; i < rrr.pois.length - 1; i++) {
          let poi = rrr.pois[i];
          if (!all_pois_count[poi]) {
            all_pois_count[poi] = 1;
          } else {
            all_pois_count[poi] += 1;
          }
        }
      }
      let mapped = map(all_pois_count);
      let maxed = max(mapped);
      let mined = min(mapped);

      let poi_data = await this.ajaxPoiData0319();
      // debugger;
      let seriesPoi = poi_data
        // .filter(poi => poi.name != "unnamed poi77")
        .map(poi => {
          let MAX_SIZE = 20;
          let MIN_SIZE = 2;
          let sizer =
            ((all_pois_count[poi.name] - mined) / (maxed - mined)) *
              (MAX_SIZE - MIN_SIZE) +
            MIN_SIZE;
          return {
            type: "custom",
            _needBrush: false,
            data: [poi.name], //poi.points,
            clip: true,
            renderItem: (params, api) => {
              let d = { ...poi };
              // debugger;
              let zoneShape = null;
              let xs = d.points[0],
                ys = d.points[1];
              if (d["save_type"] == "rect") {
                // debugger;
                // let apisized = (api)
                zoneShape = {
                  type: "polygon",
                  transition: ["shape"],
                  shape: {
                    points: [
                      [xs[0], ys[0]],
                      [xs[0], ys[1]],
                      [xs[1], ys[1]],
                      [xs[1], ys[0]]
                      // [0,0],
                      // [200000,400000],
                      // [0,200000]
                    ].map(p => api.coord(p))
                  },
                  style: {
                    stroke: "rgba(0,0,255,0.5)",
                    lineWidth: 1,
                    fill: "rgba(202,202,235,0.5)"
                  }
                };
              } else {
                zoneShape = {
                  type: "polygon",
                  shape: {
                    points: d.points.map(p => api.coord(p))
                  },
                  style: {
                    stroke: "rgba(0,0,255,0.5)",
                    lineWidth: 1,
                    fill: "rgba(202,202,235,0.5)"
                  }
                };
              }
              let textShape = {
                type: "text",
                position: [500, 500],
                style: {
                  text: String(d["name"]),
                  fill: "yellow"
                }
              };
              return {
                type: "group",
                children: [
                  // zoneShape,
                  {
                    type: "circle",
                    shape: {
                      cx: api.coord(d.center_point)[0],
                      cy: api.coord(d.center_point)[1],
                      r: 5 || sizer
                    },
                    style: {
                      fill: "white",
                      stroke: "blue"
                    }
                  }
                ]
              };
            }
          };
        });
      let guijisPois = await this.ajaxPoisOfGuiji();
      // debugger;

      // data0323
      // debugger
      // console.log(guijisPois.filter(e => e.pois.length >= 2).length, "____");
      let guiji_lines = data0323
        // .filter(e => e.pois.length >= 11 && e.pois.includes("POI-8"))
        // .slice(5, 6)

        .map(guiji => {
          let color_cluster = randomcolor({ luminosity: "dark" });
          let points = guiji.pois.map(poi_name => {
            let found = poi_data.find(p => p.name == poi_name);
            return found.center_point;
          });
          let ranking = guiji.ranking;
          let lines = points;
          return {
            coords: lines,
            lineStyle: {
              color: color_cluster
              // color:ranking<=1?"red":"black",
              // width:ranking<=1?5:2
            }
          };
          // debugger;
          // return {
          //   type: "lines",
          //   xAxisIndex: 0,
          //   yAxisIndex: 0,
          //   coordinateSystem: "cartesian2d",
          //   polyline: true,
          //   symbol: "circle",

          //   data: [
          //     {
          //       coords: lines
          //     }
          //   ],
          //   lineStyle: {
          //     color: color_cluster,
          //     opacity: 0.3,
          //     width: 4,
          //     stroke: "red"
          //   }
          // };
        });
      // debugger
      let guijiLineSeries = {
        type: "lines",
        name: "guiji",
        _needBrush: true,
        xAxisIndex: 0,
        yAxisIndex: 0,
        coordinateSystem: "cartesian2d",
        polyline: true,
        symbol: "circle",
        data: guiji_lines,
        lineStyle: {
          color: "white",
          opacity: 0.65,
          width: 2,
          stroke: "red"
        }
      };
      let tsneSeries = {
        type: "scatter",
        name: "tsne",
        _needBrush: true,
        data: data0323.map(e => [e.tsne[0], e.tsne[1], e.ranking, e.pois]),
        xAxisIndex: 1,
        yAxisIndex: 1,
        itemStyle: {
          borderWidth: 0,
          borderColor: "white",
          color: params => {
            // debugger
            // if(params.data[3].slice(1).includes("Cave")
            // &&!params.data[3].includes("POI-50")
            // ){
            //   return "blue"
            // }
            return "red";
            if (params.value[2] == 1) {
              return "red";
            }
            return "rgba(0,0,0,1)";
          },
          opacity: 0.5
        },
        symbolSize: 5
      };
      let data_kuangxuan = await this.ajaxKuangxuan();
      let polygon_series = data_kuangxuan.map(k => {
        let mined = min(flatten(k.points));
        let maxed = max(flatten(k.points));
        // debugger;
        return {
          type: "custom",
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: [[mined, k.points.length]],
          // // clip: true,
          renderItem: (params, api) => {
            // debugger
            // let dataIndex = params.dataIndex;
            let data = k.points;
            // console.log(data.points);
            // ""
            // debugger;
            return {
              type: "group",
              children: [
                {
                  type: "polygon",
                  shape: {
                    points: data.map(p => api.coord(p)),
                    // smooth:3
                  },
                  style: {
                    stroke: "rgba(0,0,0,0.5)",
                    lineWidth: 1,
                    fill: "rgba(202,202,235,0)"
                  }
                }
              ]
            };
          }
        };
      });
      return [
        guijiLineSeries,
        tsneSeries,
        seriesBackground,
        // ...seriesClusterScatter,
        ...seriesPoi,
        ...polygon_series
      ];
    }
  }
};
</script>
<style lang="less" scoped>
.thechart {
  width: 1000px;
  height: 500px;
}
.point-of-interest {
  // display: flex;
  .copypoi {
  }
  .label-info {
    position: relative;
    color: #7d0532;
    font-stretch: ultra-expanded;
    left: -250px;
    top: -22px;
    height: 0;
    width: 1000px;
  }
  .resetzoom {
    position: absolute;
    display: none;
    top: 0;
    left: 0;
  }
  .copydata {
    // display: none;
  }
  .sub-components {
    display: flex;
  }
}
</style>